package de.karlNet.sambamanager.ldapController.commands;

import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;

import org.springframework.ldap.core.LdapTemplate;

public class SimpleModificationCommand extends BaseCommand {
	private List<ModificationItem> modifications = new ArrayList<ModificationItem>();
	private String dn;

	public SimpleModificationCommand(LdapTemplate ldapTemplate, String dn) {
		this.ldapTemplate = ldapTemplate;
		this.dn = dn;
	}

	public SimpleModificationCommand simpleModificationWithoutCheck(
			BasicAttribute basicAttribute) {
		ModificationItem modificationItem = new ModificationItem(
				DirContext.REPLACE_ATTRIBUTE, basicAttribute);
		this.modifications.add(modificationItem);
		return this;
	}

	public SimpleModificationCommand simpleModification(
			BasicAttribute basicAttribute) throws NamingException {

		ModificationItem modificationItem = new ModificationItem(
				DirContext.REPLACE_ATTRIBUTE, basicAttribute);
		this.modifications.add(modificationItem);
		return this;
	}

	public void simpleModification(List<BasicAttribute> attributes)
			throws NamingException {
		for (BasicAttribute basicAttribute : attributes) {
			this.simpleModification(basicAttribute);
		}
	}

	public void execute() {
		try {
			ldapTemplate.modifyAttributes(this.dn, modifications
					.toArray(new ModificationItem[modifications.size()]));
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}
